package com.caseprocessing.interface;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 自然语言交互相关的数据模型
 */
public class ConversationModels {
    
    /**
     * 会话响应
     */
    public static class ConversationResponse {
        private String responseId;
        private String responseText;
        private ResponseType responseType;
        private double confidence;
        private List<ActionSuggestion> actionSuggestions;
        private Map<String, Object> responseData;
        private LocalDateTime responseTimestamp;
        
        public ConversationResponse() {
            this.responseId = UUID.randomUUID().toString();
            this.responseTimestamp = LocalDateTime.now();
        }
        
        // Getters and setters
        public String getResponseId() { return responseId; }
        public void setResponseId(String responseId) { this.responseId = responseId; }
        
        public String getResponseText() { return responseText; }
        public void setResponseText(String responseText) { this.responseText = responseText; }
        
        public ResponseType getResponseType() { return responseType; }
        public void setResponseType(ResponseType responseType) { this.responseType = responseType; }
        
        public double getConfidence() { return confidence; }
        public void setConfidence(double confidence) { this.confidence = confidence; }
        
        public List<ActionSuggestion> getActionSuggestions() { return actionSuggestions; }
        public void setActionSuggestions(List<ActionSuggestion> actionSuggestions) { this.actionSuggestions = actionSuggestions; }
        
        public Map<String, Object> getResponseData() { return responseData; }
        public void setResponseData(Map<String, Object> responseData) { this.responseData = responseData; }
        
        public LocalDateTime getResponseTimestamp() { return responseTimestamp; }
    }
    
    /**
     * 响应类型
     */
    public enum ResponseType {
        SUCCESS("成功响应"),
        ERROR("错误响应"),
        HELP("帮助响应"),
        EXPLANATION("解释响应"),
        ASSISTANT("助手响应"),
        CLARIFICATION("澄清响应");
        
        private final String description;
        
        ResponseType(String description) {
            this.description = description;
        }
        
        public String getDescription() { return description; }
    }
    
    /**
     * 查询意图
     */
    public static class QueryIntent {
        private String intentId;
        private QueryType queryType;
        private String specificQuery;
        private double confidence;
        private List<String> extractedEntities;
        private Map<String, Object> parameters;
        
        public QueryIntent() {
            this.intentId = UUID.randomUUID().toString();
        }
        
        // Getters and setters
        public String getIntentId() { return intentId; }
        public void setIntentId(String intentId) { this.intentId = intentId; }
        
        public QueryType getQueryType() { return queryType; }
        public void setQueryType(QueryType queryType) { this.queryType = queryType; }
        
        public String getSpecificQuery() { return specificQuery; }
        public void setSpecificQuery(String specificQuery) { this.specificQuery = specificQuery; }
        
        public double getConfidence() { return confidence; }
        public void setConfidence(double confidence) { this.confidence = confidence; }
        
        public List<String> getExtractedEntities() { return extractedEntities; }
        public void setExtractedEntities(List<String> extractedEntities) { this.extractedEntities = extractedEntities; }
        
        public Map<String, Object> getParameters() { return parameters; }
        public void setParameters(Map<String, Object> parameters) { this.parameters = parameters; }
    }
    
    /**
     * 查询类型
     */
    public enum QueryType {
        DOCUMENT_ANALYSIS("文档分析"),
        COMPLIANCE_CHECK("合规检查"),
        IMPROVEMENT_SUGGESTION("改进建议"),
        SYSTEM_EXPLANATION("系统解释"),
        GENERAL_ASSISTANCE("一般协助"),
        UNKNOWN("未知查询");
        
        private final String description;
        
        QueryType(String description) {
            this.description = description;
        }
        
        public String getDescription() { return description; }
    }
    
    /**
     * 行动建议
     */
    public static class ActionSuggestion {
        private String actionId;
        private String actionText;
        private String actionType;
        private String targetFunction;
        private Map<String, Object> parameters;
        private int priority;
        
        public ActionSuggestion() {
            this.actionId = UUID.randomUUID().toString();
        }
        
        public ActionSuggestion(String actionText, String actionType) {
            this();
            this.actionText = actionText;
            this.actionType = actionType;
        }
        
        // Getters and setters
        public String getActionId() { return actionId; }
        public void setActionId(String actionId) { this.actionId = actionId; }
        
        public String getActionText() { return actionText; }
        public void setActionText(String actionText) { this.actionText = actionText; }
        
        public String getActionType() { return actionType; }
        public void setActionType(String actionType) { this.actionType = actionType; }
        
        public String getTargetFunction() { return targetFunction; }
        public void setTargetFunction(String targetFunction) { this.targetFunction = targetFunction; }
        
        public Map<String, Object> getParameters() { return parameters; }
        public void setParameters(Map<String, Object> parameters) { this.parameters = parameters; }
        
        public int getPriority() { return priority; }
        public void setPriority(int priority) { this.priority = priority; }
    }
    
    /**
     * 会话管理器
     */
    public static class ConversationManager {
        private final Map<String, ConversationSession> activeSessions;
        private final int maxSessions;
        private final long sessionTimeoutMinutes;
        
        public ConversationManager() {
            this.activeSessions = new HashMap<>();
            this.maxSessions = 100;
            this.sessionTimeoutMinutes = 30;
        }
        
        public ConversationSession getOrCreateSession(String sessionId) {
            return activeSessions.computeIfAbsent(sessionId, id -> new ConversationSession(id));
        }
        
        public ConversationHistory getConversationHistory(String sessionId) {
            ConversationSession session = activeSessions.get(sessionId);
            return session != null ? session.getHistory() : new ConversationHistory();
        }
        
        public void clearSession(String sessionId) {
            activeSessions.remove(sessionId);
        }
        
        public int getActiveSessionCount() {
            return activeSessions.size();
        }
        
        public void cleanupExpiredSessions() {
            LocalDateTime cutoff = LocalDateTime.now().minusMinutes(sessionTimeoutMinutes);
            activeSessions.entrySet().removeIf(entry -> 
                entry.getValue().getLastActivityTime().isBefore(cutoff)
            );
        }
    }
    
    /**
     * 会话
     */
    public static class ConversationSession {
        private final String sessionId;
        private final LocalDateTime creationTime;
        private LocalDateTime lastActivityTime;
        private final ConversationHistory history;
        private QueryIntent currentIntent;
        private Map<String, Object> context;
        
        public ConversationSession(String sessionId) {
            this.sessionId = sessionId;
            this.creationTime = LocalDateTime.now();
            this.lastActivityTime = LocalDateTime.now();
            this.history = new ConversationHistory();
            this.context = new HashMap<>();
        }
        
        public void addUserMessage(String message) {
            history.addMessage(new ConversationMessage("user", message));
            updateLastActivity();
        }
        
        public void addSystemMessage(String message) {
            history.addMessage(new ConversationMessage("system", message));
            updateLastActivity();
        }
        
        private void updateLastActivity() {
            this.lastActivityTime = LocalDateTime.now();
        }
        
        // Getters and setters
        public String getSessionId() { return sessionId; }
        public LocalDateTime getCreationTime() { return creationTime; }
        public LocalDateTime getLastActivityTime() { return lastActivityTime; }
        public ConversationHistory getHistory() { return history; }
        
        public QueryIntent getCurrentIntent() { return currentIntent; }
        public void setCurrentIntent(QueryIntent currentIntent) { this.currentIntent = currentIntent; }
        
        public Map<String, Object> getContext() { return context; }
        public void setContext(Map<String, Object> context) { this.context = context; }
        
        public List<ConversationMessage> getConversationHistory() {
            return history.getMessages();
        }
    }
    
    /**
     * 会话历史
     */
    public static class ConversationHistory {
        private final List<ConversationMessage> messages;
        private final int maxMessages;
        
        public ConversationHistory() {
            this.messages = new ArrayList<>();
            this.maxMessages = 50; // 保持最近50条消息
        }
        
        public void addMessage(ConversationMessage message) {
            messages.add(message);
            
            // 保持消息数量在限制内
            if (messages.size() > maxMessages) {
                messages.subList(0, messages.size() - maxMessages).clear();
            }
        }
        
        public List<ConversationMessage> getMessages() {
            return new ArrayList<>(messages);
        }
        
        public List<ConversationMessage> getRecentMessages(int count) {
            int size = messages.size();
            int fromIndex = Math.max(0, size - count);
            return new ArrayList<>(messages.subList(fromIndex, size));
        }
        
        public String getContextSummary() {
            if (messages.isEmpty()) {
                return "新会话";
            }
            
            StringBuilder summary = new StringBuilder();
            List<ConversationMessage> recent = getRecentMessages(5);
            
            for (ConversationMessage msg : recent) {
                summary.append(msg.getRole()).append(": ")
                       .append(msg.getContent().substring(0, Math.min(50, msg.getContent().length())))
                       .append("\\n");
            }
            
            return summary.toString();
        }
    }
    
    /**
     * 会话消息
     */
    public static class ConversationMessage {
        private final String messageId;
        private final String role; // user, system, assistant
        private final String content;
        private final LocalDateTime timestamp;
        private Map<String, Object> metadata;
        
        public ConversationMessage(String role, String content) {
            this.messageId = UUID.randomUUID().toString();
            this.role = role;
            this.content = content;
            this.timestamp = LocalDateTime.now();
        }
        
        // Getters and setters
        public String getMessageId() { return messageId; }
        public String getRole() { return role; }
        public String getContent() { return content; }
        public LocalDateTime getTimestamp() { return timestamp; }
        
        public Map<String, Object> getMetadata() { return metadata; }
        public void setMetadata(Map<String, Object> metadata) { this.metadata = metadata; }
    }
    
    /**
     * 查询处理器
     */
    public static class QueryProcessor {
        private final Map<String, List<String>> intentKeywords;
        
        public QueryProcessor() {
            this.intentKeywords = initializeIntentKeywords();
        }
        
        public CompletableFuture<QueryIntent> identifyIntent(String userQuery, Map<String, Object> context) {
            return java.util.concurrent.CompletableFuture.supplyAsync(() -> {
                QueryIntent intent = new QueryIntent();
                intent.setSpecificQuery(userQuery);
                
                // 简单的关键词匹配
                String normalizedQuery = userQuery.toLowerCase();
                
                if (containsAny(normalizedQuery, intentKeywords.get("document_analysis"))) {
                    intent.setQueryType(QueryType.DOCUMENT_ANALYSIS);
                    intent.setConfidence(0.8);
                } else if (containsAny(normalizedQuery, intentKeywords.get("compliance_check"))) {
                    intent.setQueryType(QueryType.COMPLIANCE_CHECK);
                    intent.setConfidence(0.8);
                } else if (containsAny(normalizedQuery, intentKeywords.get("improvement"))) {
                    intent.setQueryType(QueryType.IMPROVEMENT_SUGGESTION);
                    intent.setConfidence(0.8);
                } else if (containsAny(normalizedQuery, intentKeywords.get("explanation"))) {
                    intent.setQueryType(QueryType.SYSTEM_EXPLANATION);
                    intent.setConfidence(0.8);
                } else if (containsAny(normalizedQuery, intentKeywords.get("general"))) {
                    intent.setQueryType(QueryType.GENERAL_ASSISTANCE);
                    intent.setConfidence(0.6);
                } else {
                    intent.setQueryType(QueryType.UNKNOWN);
                    intent.setConfidence(0.3);
                }
                
                return intent;
            });
        }
        
        private Map<String, List<String>> initializeIntentKeywords() {
            Map<String, List<String>> keywords = new HashMap<>();
            
            keywords.put("document_analysis", Arrays.asList(
                "分割", "分段", "分类", "识别", "类型", "质量", "评估", "分析"
            ));
            
            keywords.put("compliance_check", Arrays.asList(
                "合规", "检查", "验证", "风险", "问题", "错误", "规范", "标准"
            ));
            
            keywords.put("improvement", Arrays.asList(
                "建议", "改进", "优化", "修改", "完善", "提升", "增强"
            ));
            
            keywords.put("explanation", Arrays.asList(
                "原理", "工作原理", "如何", "为什么", "解释", "说明", "介绍"
            ));
            
            keywords.put("general", Arrays.asList(
                "帮助", "协助", "指导", "教程", "操作", "使用"
            ));
            
            return keywords;
        }
        
        private boolean containsAny(String text, List<String> keywords) {
            return keywords.stream().anyMatch(text::contains);
        }
    }
    
    /**
     * 响应生成器
     */
    public static class ResponseGenerator {
        
        public ConversationResponse createSuccessResponse(String responseText) {
            ConversationResponse response = new ConversationResponse();
            response.setResponseType(ResponseType.SUCCESS);
            response.setResponseText(responseText);
            response.setConfidence(0.9);
            return response;
        }
        
        public ConversationResponse createErrorResponse(String errorMessage) {
            ConversationResponse response = new ConversationResponse();
            response.setResponseType(ResponseType.ERROR);
            response.setResponseText("❌ " + errorMessage);
            response.setConfidence(0.9);
            
            // 添加帮助建议
            List<ActionSuggestion> suggestions = Arrays.asList(
                new ActionSuggestion("查看帮助文档", "help"),
                new ActionSuggestion("重新描述问题", "retry")
            );
            response.setActionSuggestions(suggestions);
            
            return response;
        }
        
        public ConversationResponse createHelpResponse(String helpText) {
            ConversationResponse response = new ConversationResponse();
            response.setResponseType(ResponseType.HELP);
            response.setResponseText("💡 " + helpText);
            response.setConfidence(0.9);
            return response;
        }
        
        public ConversationResponse createExplanationResponse(String explanation) {
            ConversationResponse response = new ConversationResponse();
            response.setResponseType(ResponseType.EXPLANATION);
            response.setResponseText("📖 " + explanation);
            response.setConfidence(0.9);
            
            // 添加相关操作建议
            List<ActionSuggestion> suggestions = Arrays.asList(
                new ActionSuggestion("尝试相关功能", "try_function"),
                new ActionSuggestion("了解更多详情", "more_details")
            );
            response.setActionSuggestions(suggestions);
            
            return response;
        }
        
        public ConversationResponse createAssistantResponse(String assistantText) {
            ConversationResponse response = new ConversationResponse();
            response.setResponseType(ResponseType.ASSISTANT);
            response.setResponseText("🤖 " + assistantText);
            response.setConfidence(0.8);
            return response;
        }
        
        public ConversationResponse createClarificationResponse(String clarificationText) {
            ConversationResponse response = new ConversationResponse();
            response.setResponseType(ResponseType.CLARIFICATION);
            response.setResponseText("❓ " + clarificationText);
            response.setConfidence(0.7);
            
            // 添加澄清选项
            List<ActionSuggestion> suggestions = Arrays.asList(
                new ActionSuggestion("是的，继续", "confirm"),
                new ActionSuggestion("不是，重新解释", "clarify")
            );
            response.setActionSuggestions(suggestions);
            
            return response;
        }
        
        public ConversationResponse createResponseWithData(
                String responseText, 
                ResponseType type, 
                Map<String, Object> data) {
            
            ConversationResponse response = new ConversationResponse();
            response.setResponseType(type);
            response.setResponseText(responseText);
            response.setResponseData(data);
            response.setConfidence(0.9);
            return response;
        }
    }
}